package com.aivin.maproutelib.tool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import java.io.InputStream;


public final class BitmapTool {

    public static Bitmap rotateBitmap(Context context, int resId, float degrees) {
        Bitmap bitmap =  readBitmapById(context, resId);
        return rotateBitmap( bitmap, degrees);
    }

    /**
     * 通过资源id转化成Bitmap
     */
    public static Bitmap readBitmapById(Context context, int resId)  {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;

        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }


    /**
     * 旋转图片
     */
    private static Bitmap rotateBitmap(Bitmap bitmap, float degrees)  {
        if(bitmap==null){
            return null ;
        }
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(degrees);

        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        if (resizedBitmap != bitmap  && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        return resizedBitmap;
    }

}
